import 'package:auto_route/auto_route.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:sonora/bloc/base/sj_base_bloc.dart';
import 'package:sonora/bloc/login/sj_login_event.dart';
import 'package:sonora/bloc/login/sj_login_state.dart';
import 'package:sonora/models/sj_login_response_data.dart';
import 'package:sonora/models/sj_response_data.dart';
import 'package:sonora/services/sj_api_login_service.dart';
import 'package:sonora/utils/sj_device_utils.dart';
import 'package:sonora/utils/sj_log_utils.dart';
import 'package:sonora/utils/sj_storage_utils.dart';
import 'package:sonora/views/navigation/routes/sj_app_router.dart';

class SjLoginBloc extends SjBaseBloc<SjLoginEvent, SjLoginState> {
  SjLoginBloc() : super(const SjLoginState()) {
    on<AppleLoginRequested>(_onAppleLoginRequest);
    on<FastLoginRequested>(_onFastLoginRequest);
    on<LoginEventSuccess>(_onLoginSuccess);
    on<LoginEventFailure>(_onLoginFailure);
    on<LoginEventToggleUse>(_onToggleUse);
    on<LoginEventTogglePrivacy>(_onTogglePrivacy);
  }

  Future<void> _onAppleLoginRequest(
      AppleLoginRequested event, Emitter<SjLoginState> emit) async {
    emit(state.copyWith(initial: true));
    try {
      final credential = await SignInWithApple.getAppleIDCredential(scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName
      ]);
      if (credential.userIdentifier != null) {
        SjLoginResponseData responseData =
            await SjApiLoginService().appleLogin(credential.identityToken!);
        if (responseData.success != null &&
            responseData.success! == true &&
            responseData.data != null) {
          SjStorageUtils.saveLoginInfo(responseData.data!.toJson());
          // event.context.router.pushAndPopUntil(
          //   const SjMainRoute(),
          //   predicate: (route) => false, // 清空栈
          // );

          event.context.router.replaceAll([const SjMainRoute()]);
          
          SjLogPvManger.stat(page: SjLogPages.sjPageNameLoginsuccess);
        } else {}
      } else {}
      emit(state.copyWith(userIdentifier: credential.userIdentifier ?? ''));
    } catch (e) {
      emit(state.copyWith(error: e.toString()));
    }
  }

  Future<void> _onFastLoginRequest(
      FastLoginRequested event, Emitter<SjLoginState> emit) async {
    final token = await SjDeviceUtils.getUdid();
    SjLoginResponseData responseData =
        await SjApiLoginService().fastLogin(token ?? '');
    if (responseData.success != null &&
        responseData.success! == true &&
        responseData.data != null) {
      SjStorageUtils.saveLoginInfo(responseData.data!.toJson());
      emit(state.copyWith(oauthType: event.oauthType));
      // event.context.router.pushAndPopUntil(
      //   SjMainRoute(),
      //   predicate: (route) => false, // 清空栈
      // );
      event.context.router.replaceAll([const SjMainRoute()]);
      SjLogPvManger.stat(page: SjLogPages.sjPageNameLoginsuccess);
    } else {}
  }

  void _onLoginSuccess(LoginEventSuccess event, Emitter<SjLoginState> emit) {
    emit(state.copyWith(userIdentifier: event.userIdentifier));
  }

  void _onLoginFailure(LoginEventFailure event, Emitter<SjLoginState> emit) {
    emit(state.copyWith(error: event.error));
  }

  void _onToggleUse(LoginEventToggleUse event, Emitter<SjLoginState> emit) {
    emit(state.copyWith(useChecked: !event.useChecked));
  }

  void _onTogglePrivacy(
      LoginEventTogglePrivacy event, Emitter<SjLoginState> emit) {
    emit(state.copyWith(privacyChecked: !event.privacyChecked));
  }
}
